"use client";

import { useNotifications } from "@/app/hooks/notification.hook";
import { GATEWAY_URL } from "@/lib/env";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

export default function SignUpPage() {
  const { showError } = useNotifications();
  const router = useRouter();
  const [state, setState] = useState({
    email: "",
    password: "",
    name: "",
    phone: "",
  });

  function handleChange(e) {
    setState((prev) => {
      return { ...prev, [e.target.name]: e.target.value };
    });
  }

  async function handleSubmit() {
    if (
      state.email.length < 1 ||
      state.email.length < 1 ||
      state.password.length < 1 ||
      state.name.length < 1 ||
      state.phone.length < 1
    ) {
      showError("Необходимо заполнить все поля");
      return;
    }

    const res = await fetch(`${GATEWAY_URL}/auth/sign-up`, {
      method: "POST",
      body: JSON.stringify(state),
      headers: {
        "Content-Type": "application/json",
      },
    });
    const json = await res.json();
    console.log(json);

    if (res.ok) {
      localStorage.setItem("token", json.accessToken);
      router.push("/me");
    } else {
      alert(json.message ?? "Неверный email или пароль");
    }
  }

  useEffect(() => {
    if (localStorage.getItem("token")) {
      router.push("/me");
      return;
    }
  }, []);

  return (
    <section className="sign-in" id="sign-in" style={{ flex: 2 }}>
      <h1 className="heading">
        Реги<span>страция</span>
      </h1>
      <div className="inputBox">
        <span className="fas fa-user"></span>
        <input
          onChange={handleChange}
          type="text"
          placeholder="Имя"
          name="name"
          value={state.name}
        />
      </div>
      <div className="inputBox">
        <span className="fa fa-mobile"></span>
        <input
          onChange={handleChange}
          type="text"
          placeholder="Номер телефона"
          name="phone"
          value={state.phone}
        />
      </div>
      <div className="inputBox">
        <span className="fa fa-envelope-o"></span>
        <input
          onChange={handleChange}
          type="text"
          placeholder="Email"
          name="email"
          value={state.email}
        />
      </div>
      <div className="inputBox">
        <span className="fas  fa-unlock-alt"></span>
        <input
          type="password"
          placeholder="Пароль"
          name="password"
          value={state.password}
          onChange={handleChange}
        />
      </div>
      <input
        type="submit"
        value="Зарегистрироваться"
        className="btn"
        onClick={() => handleSubmit()}
      />
    </section>
  );
}
